<?php

namespace interface\v1;
/*
*工资条接口类
*/

class paySlipAppClass extends index
{
    private const title = '工资条';
    private const page = 'paySlip';
    private const table = 'work_sign_record';

    /*列表页*/
    public function home()
    {
        $data['result']=[];
        $type = $this->post('type');
        $month = $this->post('month') ?: date('Y-m');
        $info = query(self::table, "stid = '" . self::$stid . "' and month = '$month'");
        $auditFollow = find(array('table'=>'auditing_follow','where'=>"typeId = '$info[id]' order by time asc"));
        $record = [];
        foreach ($auditFollow['array'] as $array){
            $record[] = $array['text'];
        }
        if ($type =='计时计件'){
            $all = find(array("table" => "timing_report","where" => "coid = '".self::$coid."' and staffId = '".self::$stid."' and date_format(recordDate,'%Y-%m') = '$month'",'order'=>"recordDate desc"));
            foreach ($all['array'] as $array){
                $teamMx = query('team_detail',"orderId = '$array[teamId]' and stid = '$array[staffId]'");
                $data['result'][] = [
                    'recordDate'=>$array['recordDate'],
                    'hour'=>$array['hour'],
                    'type'=>'计时工资',
                    'price'=>$teamMx['price'],
                    'money'=>round($array['hour']*$teamMx['price'],2),
                ];
            }
            $all = find(array("table" => "process_report_staff as a join process_report as b on a.orderId = b.id join machining_send_order as ma on ma.id = b.sendId",
                'field'=>"b.*,a.stid as teamStid,ma.unit as fromUnit,ma.machiningOrderMxId,ma.orderNo as sendNo","where" => "b.state = '已确认' and b.coid = '".self::$coid."' and date_format(teamNo,'%Y-%m') = '$month' and b.classify = '工序报工' and a.stid = '".self::$stid."'", "order" => "b.teamNo desc,a.list"));
            foreach ($all['array'] as $array){
                $material = query('material',"id = '$array[materialId]'");
                $process = query('process',"id = '$array[processId]'");
                $array['yield'] = self::material_num_change($array['materialSkuId'],$array['fromUnit'],$material['unit'],$array['yield']);
                $routMx = query('routing_detail',"id = '$array[routingMxId]'");
                $routMx['price']=$routMx['price']?:0;
                $salary = round($routMx['price']*$array['yield'],2);
                if ($array['valuationType'] =='个人计件'){
                    $personMoney = $salary;
                }else{
                    $team_detail = query('team_detail',"orderId = '$array[teamId]' and stid = '$array[teamStid]'");
                    $team_detail['rate'] = $team_detail['rate']?:0;
                    //当前班组人员考勤
                    $workshop_clock_detail = find(array('table'=>'workshop_clock as a join workshop_clock_detail as b on a.id = b.orderId','single'=>"a.state !='草稿' and a.teamId like '%$array[teamId]%' and b.stid = '$array[teamStid]' and b.recordDate = '$array[teamNo]'",'field'=>"b.hour"));
                    $workshop_clock_detail['hour'] = $workshop_clock_detail['hour']??0;
                    $rateSum = $this->caculate($array['teamId'],$array['teamNo']);
                    //公式  计件工资*（个人计件系数*个人考勤）/(班组中每个人的(个人考勤*个人系数)之和)
                    $personMoney =$rateSum>0? round($salary*($team_detail['rate']*$workshop_clock_detail['hour']/$rateSum),2):0;
                }
                $data['result'][] = [
                    'recordDate'=>$array['teamNo'],
                    'orderNo'=>$array['orderNo'],
                    'type'=>'计件工资',
                    'materialName'=>self::getName($array['materialSkuId']),
                    'process'=>$process['name'],
                    'num'=>$array['yield'].$array['unit'],
                    'price'=>$routMx['price'],
                    'totalMoney'=>$salary,
                    'money'=>$personMoney,
                ];
            }
        }else{
            if (is_array($info)) {
                foreach ($info as $k => $val) {
                    $info['money']=(float)$info['money'];
                    $info['insure']=(float)$info['insure'];
                    $info['providentFund']=(float)$info['providentFund'];
                    $info['income'] = $info['money']-$info['insure']-$info['providentFund'];
                    $info[$k] = empty($val) ? '-' : $val;
                }
                $data['result'] = $info;
            }

        }



        $data['record'] = $record;
        //返回
        $this->code = 1;
        $this->resp['data'] = $data;
    }
    /**
     * 计算 计件系数和计件工时和
     */
    public function caculate($teamId,$date): float|int
    {
        $total = 0;
        $team_detail = find(array('table'=>'team_detail','where'=>"orderId = '$teamId'"));
        foreach ($team_detail['array'] as $array){
            $workshop_clock_detail = find(array('table'=>'workshop_clock as a join workshop_clock_detail as b on a.id = b.orderId','single'=>"a.state !='草稿' and a.teamId like '%$teamId%' and b.stid = '$array[stid]' and b.recordDate = '$date'",'field'=>"b.hour"));
            $workshop_clock_detail['hour'] = $workshop_clock_detail['hour']??0;
            $total+=$array['rate']*$workshop_clock_detail['hour'];
        }
        return $total;
    }
    /**
     * 物料单位转换
     *
     * @param     $materialSkuId
     * @param     $from
     * @param     $to
     * @param int $num
     * @return int|float
     */
    public static function material_num_change($materialSkuId, $from, $to, $num = 1): int|float
    {
        $num = $num ?: 0;
        if ($from == $to) {
            return $num;
        }
        $materialSku = query('material_sku', " id = '$materialSkuId'");
        $material = query('material', " id = '$materialSku[materialId]'");
        $materialSku['unitOne'] = (float)$materialSku['unitOne'];
        $materialSku['unitTwo'] = (float)$materialSku['unitTwo'];
        if ($from == $material['unit_one']) {
            $num = $materialSku['unitOne'] * $num;
        } elseif ($from == $material['unit_two']) {
            $num = $materialSku['unitTwo'] * $num;
        }
        if ($to == $material['unit_one']) {
            $num = $materialSku['unitOne'] > 0 ? round($num / $materialSku['unitOne'], 2) : 0;
        } elseif ($to == $material['unit_two']) {
            $num = $materialSku['unitTwo'] > 0 ? round($num / $materialSku['unitTwo'], 2) : 0;
        }
        return $num;
    }
    /**
     * 获取物料名称
     * @param $id
     * @param string $interval
     * @return string
     */
    public static function getName($id, $interval = '-'): string
    {
        $name = '';
        $materialSku = query('material_sku', "id = '$id'");
        $material = query(self::table, "id = '$materialSku[materialId]'");
        if (!$material['id']) {
            $material = query(self::table, "id = '$id'");
        }
        if (empty($material['id'])) {
            return $name;
        }
        $name .= $material['code'] ? ($material['code'] . $interval) : '';
        $name .= $material['name'] ? ($material['name'] . $interval) : '';
        $name .= $material['model'] ? ($material['model'] . $interval) : '';
        if ($materialSku['id']) {
            $name .= $materialSku['name'] ? ($materialSku['name'] . $interval) : '';
        }
        return rtrim($name, $interval);
    }

    /**
     * 确认
     */
    public function confirmEdit()
    {
        $id = $this->post('id');
        $where = " id = '$id' ";
        $info = query(self::table, $where);
        //判断
        if (empty($info['id'])) {
            $this->resp['warn'] = "未找到此工资条";
        } elseif ($info['isConfirm'] != '待确认') {
            $this->resp['warn'] = '此工资已确认，无需重复操作';
        } else {
            $this->resp['warn'] = static::update([
                "table" => self::table,
                "field" => ['isConfirm' => '已确认'],
                "where" => $where
            ]);
            if (in_array($this->resp['warn'], ["新增成功", "更新成功"])) {
                auditingFollow(array(
                    "type" => "工资确认",
                    "typeId" => $info['id'],
                    "text" => "【{$this->control['name']}】于【{$this->time}】确认【{$info['month']}】月工资",
                ));
                //添加日志
                $type = mb_substr($this->resp['warn'], 0, 2, 'utf-8');
                $text = $this->control['name'] . $type . "了" . self::title . " id：【" . $id . '】';
                $this->logText(["type" => self::page, "text" => $text]);
                //返回
                $this->code = 1;
                $this->resp['warn'] = '确认成功';
                $this->resp['data']['month'] = $info['month'];
            }
        }

        resp:
    }

}
